package com.pesking.core.sqlparser.processor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.pesking.core.exception.SystemException;
import com.pesking.core.parameter.JsonRequestParameter;
import com.pesking.core.parameter.Parameter;
import com.pesking.core.sqlparser.parameter.SqlParameter;
import com.pesking.core.sqlparser.parameter.SqlParameterProcessor;
import com.pesking.core.util.StringUtils;

public class JSONSqlParameterHandler extends SqlParameterProcessor {

	
	@Override
	public void handle(StringBuilder sbSQL, Parameter parameter, List<SqlParameter> processors,SqlParameter sqlParameter) {
		String jsonObjectName = sqlParameter.getName();
		String jsonPath       = sqlParameter.getField();
		if (StringUtils.isBlank(jsonObjectName) || StringUtils.isBlank(jsonPath)){
			throw new SystemException("JSON参数对应的值未能取到，正确的编写格式为：[JSON:jsonObjectname:path]");
		}
		Object jsonObject = parameter.getAttribute(jsonObjectName);
		List<String> jsonPaths = new ArrayList<String>(1);
		jsonPaths.add(jsonPath);
		List<String> values = JsonRequestParameter.getJsonNodeValue(jsonObject,jsonPaths,parameter);
		String value = null;
		if (values != null && values.size() > 0){
			value = values.get(0);
		}
		if (value == null){
			value = "";
		}
		sbSQL.append(value);
	}
		
	@Override
	public List<String> getSqlParameterType() {
		return Arrays.asList(new String []{"JSON"});
	}
}
